<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<view class="content-bgc">
			<view class="b-con">
				<uni-forms :model="form" :rules="rules" ref="refForm" label-width="100px">
					<uni-forms-item label="编号" name="code" required>
						<view style="display: flex;gap:20rpx">
							<uni-easyinput v-model="form.code" placeholder="请输入编号" class="iptBor" :inputBorder="false"
								:disabled="switchCode" />
							<view style="margin-left: 20rpx" v-show="pageInfo.type == 'add'">
								<u-switch v-model="switchCode" @change="switchChange" size="20" />
								自动生成
							</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="维修设备" name="equipment" required>
						<uni-data-select v-model="form.equipment" :localdata="device_list" placeholder="请选择维修设备" mode="underline"
							:clear="false" />
					</uni-forms-item>
					<uni-forms-item label="维修主题" name="title" required>
						<uni-easyinput v-model="form.title" placeholder="请输入维修主题" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="故障描述">
						<uni-easyinput v-model="form.fault_description" type="textarea" placeholder="请输入故障描述" />
					</uni-forms-item>
					<uni-forms-item label="附件">
						<uni-file-picker v-model="form.file_urls" file-mediatype="image" file-extname="png,jpg,jpeg" @select="select"
							title="只能上传jpg/png/jpeg文件，且建议大小不超过2M"></uni-file-picker>
					</uni-forms-item>
					<u-button type="primary" text="提交" @click="save" />
				</uni-forms>
			</view>
		</view>
	</view>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import deRepairApi from '../../../api/device/de_repair'
import { BASE_URL } from '../../../common/request';
import { generateCode } from '@/utils/index.js';

//页面标题
const pageInfo = reactive({
	navbarTitle: '设备档案',
	type: '',
	edit_id: null,
})

onLoad((option) => {
	get_device_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(修改)`
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(新增)`
		form.code = generateCode('RE')
	}
})

//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('RE')
	}
}

const refForm = ref(null);
const form = reactive({
	code: '',
	equipment: null,
	title: '',
	fault_description: '',
	file_urls: []
});
const fields = Object.keys(form)
const rules = {
	code: { rules: [{ required: true, errorMessage: '请输入设备编号' }] },
	title: { rules: [{ required: true, errorMessage: '请输入维修主题' }] },
	equipment: { rules: [{ required: true, errorMessage: '请选择维修设备' }] },
};

//详情
function get_detail(id) {
	deRepairApi.repair_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields) //过滤表单需要的字段
		record.file_urls = record.file_urls.split(',').map(v => ({
			name: 'file.txt',
			extname: "txt",
			url: v,
		}))
		Object.assign(form, record)
	})
};

// 上传
const action = BASE_URL + '/file/';
const token = uni.getStorageSync("assecss_token");
function select({ tempFiles }) {
	uni.uploadFile({
		url: action, //
		filePath: tempFiles[0].path,
		name: 'file',
		header: {
			'Authorization': "JWT " + token
		},
		success: (files) => {
			const data = JSON.parse(files.data)
			form.file_urls.push({
				name: 'file.txt',
				extname: "txt",
				url: data.file,
			})
		},
		fail: (err) => {
			uni.$u.toast('上传图片失败')
		}
	});
};
//提交表单
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		params.file_urls = params.file_urls.map(v => v.url).join(',')
		if (pageInfo.type == 'add') {
			deRepairApi.post_repair(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			deRepairApi.patch_repair(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}
	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})

}

const device_list = ref([]);
function get_device_list() {
	deRepairApi.get_device({ page: 1, page_size: 99999 }).then(res => {
		device_list.value = res.results.map(v => ({
			text: v.name,
			value: v.id
		}))
	})
};

//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('de_repair');
		}
	})
};
</script>

<style lang="scss" scoped></style>